package com.resource.controller;

import java.io.IOException;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections4.ListUtils;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.excel.metadata.Sheet;
import com.resource.dto.*;
import com.resource.excel.ProjectTeam;
import com.resource.query.ProjectQuery;
import com.resource.query.ProjectValidateQuery;
import com.resource.request.ProjectValidateRequest;
import com.resource.service.OfficeProjectService;
import com.resource.utils.EasyExcelUtil;
import com.resource.utils.ResultBody;
import com.resource.utils.ServiceResultHandler;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 项目管理模块
 *
 * @Author: xianggaoxiong
 * @Date: 2020-09-23 21:22
 **/
@Slf4j
@RestController
@RequestMapping(value = "/api/project")
public class OfficeProjectController {
	@Resource
	private OfficeProjectService projectService;

	@RequestMapping("/getTask")
	public ResultBody getTask(HttpServletRequest request) {
		System.out.println("-----------------测试---------------");
		return ResultBody.builder().success().build();
	}


	/**
	 * 通过查询条件获取列表
	 *
	 * @param projectQuery
	 * @return
	 */
	@GetMapping("/getProjectList")
	public ResultBody getProjectList(ProjectQuery projectQuery) {
		return ServiceResultHandler
				.process((Function<Object, Object>) o -> projectService.getProjectList((ProjectQuery) o), projectQuery);
	}

	/**
	 * 通过id获取详情
	 *
	 * @param managerId
	 * @return
	 */
	@GetMapping("/getProjectInfo/{managerId}")
	public ResultBody getProjectInfo(@PathVariable(value = "managerId") Integer managerId) {
		return ServiceResultHandler
				.process((Function<Object, Object>) o -> projectService.getProjectInfoById((Integer) o), managerId);
	}

	/**
	 * 添加项目信息
	 *
	 * @param dto
	 * @return
	 */
	@PostMapping("/addProject")
	public ResultBody addProject(@RequestBody OfficeProjectInfoDto dto) {
		return ServiceResultHandler
				.process((Consumer<Object>) (o) -> projectService.addProject((OfficeProjectInfoDto) o), dto);
	}

	/**
	 * 删除项目信息
	 *
	 * @param managerId
	 * @return
	 */
	@DeleteMapping("/removeProject/{managerId}")
	public ResultBody removeProject(@PathVariable("managerId") Integer managerId) {
		return ServiceResultHandler.process((Consumer<Object>) (o) -> projectService.removeProject((Integer) o),
				managerId);
	}

	/**
	 * 更新项目信息
	 *
	 * @param dto
	 * @return
	 */
	@PutMapping("/modifyProject")
	public ResultBody modifyProject(@RequestBody OfficeProjectInfoDto dto) {
		return ServiceResultHandler
				.process((Consumer<Object>) (o) -> projectService.modifyProject((OfficeProjectInfoDto) o), dto);
	}

	/**
	 * 通过查询条件获取列表
	 *
	 * @param request
	 * @return
	 */
	@PostMapping("/processForm/validate")
	public String processFormValidate(ProjectValidateRequest request) {
		ProjectValidateQuery build = ProjectValidateQuery.builder().manager_number(request.getDATA_44())
				.manager_name(request.getDATA_45()).build();
		return projectService.processFormValidate(build);
	}

	/**
	 * 项目外发，更新合同的关联关系
	 *
	 * @param request
	 * @return
	 */
	@PostMapping("/contract")
	public ResultBody modifyContract(HttpServletRequest request) {
		String managerNumber = request.getParameter("DATA_44");
		String managerName = request.getParameter("DATA_45");
		String managerType = request.getParameter("DATA_43");
		String userId = request.getParameter("DATA_53");
		ProjectQuery projectQuery = ProjectQuery.builder().userId(userId).manager_number(managerNumber)
				.manager_name(managerName).manager_type(managerType).build();
		return ServiceResultHandler.process((Consumer<Object>) (o) -> projectService.modifyContract((ProjectQuery) o),
				projectQuery);
	}

	/**
	 * 项目导入
	 * 
	 * @param file
	 * @return
	 */
	@PostMapping("/import")
	public String importProject(MultipartFile file) {
		List<Object> list = new ArrayList<>();
		try {
			list = EasyExcelUtil.readExcel(file, new ProjectImportDto(), 1, 1);
		} catch (IOException e) {
			log.error("excel resolve fail:", e);
			return "fail";
		}

		List<List<Object>> partition = ListUtils.partition(list, list.size() / 5);
		log.info("线程处理数量:{}", partition.size());
		for (int i = 0; i < partition.size(); i++) {
			List<Object> objects = partition.get(i);
			new Thread(() -> {
				objects.stream().forEach(e -> {
					try {
						ProjectImportDto dto = (ProjectImportDto) e;
						if (StrUtil.isNotEmpty(dto.getTemp_data())) {
							dto.setCarrier_goods(StrUtil.splitToInt(dto.getTemp_data(), ","));
							dto.setTemp_data(null);
						}
						projectService.importProject(dto);
					} catch (Exception ex) {
						log.error("{}数据处理失败：{},", Thread.currentThread().getName(), JSONUtil.toJsonStr(e));
					}
				});
				log.info("{}处理完成", Thread.currentThread().getName());
			}, i + "任务").start();
		}

		return "处理中。。。。。。";
	}

	/**
	 * 任务导入
	 * 
	 * @param file
	 * @return
	 */
	@PostMapping("/import/task")
	public String importTask(MultipartFile file) {
		List<Object> list = new ArrayList<>();
		try {
			list = EasyExcelUtil.readExcel(file, new ProjectTaskImportDto(), 1, 1);
		} catch (IOException e) {
			log.error("excel resolve fail:", e);
			return "fail";
		}

		List<List<Object>> partition = ListUtils.partition(list, list.size() / 5);
		log.info("线程处理数量:{}", partition.size());
		for (int i = 0; i < partition.size(); i++) {
			List<Object> objects = partition.get(i);
			new Thread(() -> {
				objects.stream().forEach(e -> {
					try {
						ProjectTaskImportDto dto = (ProjectTaskImportDto) e;
						projectService.importProjectTask(dto, dto.getUser_id());
					} catch (Exception ex) {
						log.error("{}数据处理失败：{},", Thread.currentThread().getName(), JSONUtil.toJsonStr(e));
					}
				});
				log.info("{}处理完成", Thread.currentThread().getName());
			}, i + "任务").start();
		}
		return "处理中。。。。。。";
	}

	/**
	 * 项目导出
	 * 
	 * @return
	 */
	@GetMapping("/export")
	public String exportProject() {
		List<JSONObject> jsonObjects = projectService.exportProject();
		if (CollUtil.isNotEmpty(jsonObjects)) {
			new Thread(() -> {
				List<ProjectExportDto> exportDtos = jsonObjects.stream()
						.map(e -> ProjectExportDto.builder().id(e.getStr("manager_id"))
								.manager_number(e.getStr("manager_number")).manager_name(e.getStr("manager_name"))
								.build())
						.collect(Collectors.toList());
				EasyExcelUtil.writeWithTemplate("C:\\project_export.xlsx", exportDtos);
				log.info("项目导出处理完成！");
			}).start();
		}
		return "处理中。。。。。。";
	}

	@GetMapping("/team")
	public String teamMember() {
		Sheet sheet = new Sheet(1, 1);
		String filePath = "C:\\member.xlsx";
		List<Object> members = EasyExcelUtil.readMoreThan1000RowBySheet(filePath, sheet);

		String filePath2 = "C:\\project_member.xlsx";
		List<Object> projectMembers = EasyExcelUtil.readMoreThan1000RowBySheet(filePath2, sheet);

		Map<String, String> memberMap = new HashMap<>(members.size() * 2);
		members.forEach(e -> {
			List<String> member = (ArrayList) e;
			memberMap.put(member.get(0), member.get(1));
		});

		List<ProjectTeam> teams = new LinkedList<>();
		projectMembers.forEach(e -> {
			List<String> member = (ArrayList) e;
			List<String> split = StrUtil.split(member.get(1), ',');
			String collect = split.stream().filter(c -> StrUtil.isNotEmpty(memberMap.get(c))).map(b -> memberMap.get(b))
					.collect(Collectors.joining(","));
			ProjectTeam build = ProjectTeam.builder().projectCode(member.get(0)).teams(collect).build();
			teams.add(build);
		});
		EasyExcelUtil.writeWithTemplate("C:\\project_team.xlsx", teams);
		log.info("项目导出处理完成！");
		return "处理中。。。。。。";
	}

	/**
	 * 项目导入
	 * 
	 * @param file
	 * @return
	 */
	@PostMapping("/import/update")
	public String importUpdateProject(MultipartFile file) {
		List<Object> list = new ArrayList<>();
		try {
			list = EasyExcelUtil.readExcel(file, new ProjectUpdateImportDto(), 1, 1);
		} catch (IOException e) {
			log.error("excel resolve fail:", e);
			return "fail";
		}

		List<List<Object>> partition = ListUtils.partition(list, list.size() / 6);
		log.info("线程处理数量:{}", partition.size());
		for (int i = 0; i < partition.size(); i++) {
			List<Object> objects = partition.get(i);
			new Thread(() -> {
				objects.stream().forEach(e -> {
					try {
						ProjectUpdateImportDto dto = (ProjectUpdateImportDto) e;
						projectService.importUpdateProject(dto);
					} catch (Exception ex) {
						log.error("{}数据处理失败：{},", Thread.currentThread().getName(), JSONUtil.toJsonStr(e));
					}
				});
				log.info("{}处理完成", Thread.currentThread().getName());
			}, i + "任务").start();
		}

		return "处理中。。。。。。";
	}

	@RequestMapping("getInfo")
    public List<JSONObject> getInfo(HttpServletRequest httpServletRequest){
		String[] data_1131s = httpServletRequest.getParameterMap().get("DATA_1131");
		JSONObject jsonObject=new JSONObject();
        jsonObject.putOpt("DATA_1112_0","2020-11-11 14:55:55");
        jsonObject.putOpt("DATA_1112_7","2020-11-12 14:55:55");
		JSONObject city=new JSONObject();
		city.putOpt("province","18");
		city.putOpt("city","182");
		city.putOpt("district","1696");
		JSONObject city2=new JSONObject();
		city2.putOpt("province","1");
		city2.putOpt("city","1");
		city2.putOpt("district","5");
		jsonObject.putOpt("DATA_1112_8",city);
		jsonObject.putOpt("DATA_1112_9",city2);
        JSONObject jsonObject1=new JSONObject();
        jsonObject1.putOpt("DATA_1112_0","2020-11-11 14:55:55");
        jsonObject1.putOpt("DATA_1112_7","2020-11-12 14:55:55");
        JSONObject jsonObject2=new JSONObject();
        jsonObject2.putOpt("DATA_1112_0","2020-11-11 14:55:55");
        jsonObject2.putOpt("DATA_1112_7","2020-11-12 14:55:55");
        List<JSONObject> result=new ArrayList<>();
        result.add(jsonObject);
        result.add(jsonObject1);
        result.add(jsonObject2);
        return result;
    }



}
